/**
 * Copyright &copy; 2012-2017 <a href="https://vivo.com/">vivo</a> All rights reserved.
 */
package com.vivo.system.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.vivo.dingtalk.auth.AuthHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.vivo.system.entity.VivoDingConf;
import com.vivo.system.service.VivoDingConfService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 钉钉接入管理Controller
 * @author jyangye
 * @version 2018-05-11
 */
@Controller
@RequestMapping(value = "${adminPath}/system/vivoDingConf")
public class VivoDingConfController extends BaseController {

	@Autowired
	private VivoDingConfService vivoDingConfService;

	@Autowired
    private OfficeService officeService;
	
	@ModelAttribute
	public VivoDingConf get(@RequestParam(required=false) String id) {
		VivoDingConf entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = vivoDingConfService.get(id);
		}
		if (entity == null){
			entity = new VivoDingConf();
		}
		return entity;
	}
	
	@RequiresPermissions("system:vivoDingConf:view")
	@RequestMapping(value = {"list", ""})
	public String list(VivoDingConf vivoDingConf, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<VivoDingConf> page = vivoDingConfService.findPage(new Page<VivoDingConf>(request, response), vivoDingConf); 
		model.addAttribute("page", page);

		List<Office> compList = officeService.getCompanyList();
		List<Dict> dictList = new ArrayList<Dict>();
		for (Office comp : compList) {
		    Dict dict = new Dict();
		    dict.setValue(comp.getId());
		    dict.setLabel(comp.getName());
		    dictList.add(dict);
        }

        model.addAttribute("compList", dictList);

		return "vivo/system/vivoDingConfList";
	}

	@RequiresPermissions("system:vivoDingConf:view")
	@RequestMapping(value = "form")
	public String form(VivoDingConf vivoDingConf, Model model) {
		model.addAttribute("vivoDingConf", vivoDingConf);
        List<Office> compList = officeService.getCompanyList();
        List<Dict> dictList = new ArrayList<Dict>();
        for (Office comp : compList) {
            Dict dict = new Dict();
            dict.setValue(comp.getId());
            dict.setLabel(comp.getName());
            dictList.add(dict);
        }

        model.addAttribute("compList", dictList);
		return "vivo/system/vivoDingConfForm";
	}

	@RequiresPermissions("system:vivoDingConf:edit")
	@RequestMapping(value = "save")
	public String save(VivoDingConf vivoDingConf, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, vivoDingConf)){
			return form(vivoDingConf, model);
		}
		vivoDingConfService.save(vivoDingConf);
		addMessage(redirectAttributes, "保存钉钉接入管理成功");
		return "redirect:"+Global.getAdminPath()+"/system/vivoDingConf/?repage";
	}
	
	@RequiresPermissions("system:vivoDingConf:edit")
	@RequestMapping(value = "delete")
	public String delete(VivoDingConf vivoDingConf, RedirectAttributes redirectAttributes) {
		vivoDingConfService.delete(vivoDingConf);
		addMessage(redirectAttributes, "删除钉钉接入管理成功");
		return "redirect:"+Global.getAdminPath()+"/system/vivoDingConf/?repage";
	}


	@RequiresPermissions("system:vivoDingConf:edit")
	@RequestMapping(value = "active")
	public String active(VivoDingConf vivoDingConf, RedirectAttributes redirectAttributes) {
	    refreshToken(vivoDingConf);
		addMessage(redirectAttributes, "钉钉更新token成功");
		return "redirect:"+Global.getAdminPath()+"/system/vivoDingConf/?repage";
	}

	private void refreshToken(VivoDingConf vivoDingConf) {
	    // 获取access_token
        String accessToken = null;
        String ticket = null;
        try {
            accessToken = AuthHelper.getAccessToken(vivoDingConf.getCorpId(), vivoDingConf.getCorpSecret());
            ticket = AuthHelper.getJsapiTicket(accessToken);
        }catch (Exception e) {
            e.printStackTrace();
        }

        if (accessToken != null && ticket != null) {
            vivoDingConf.setAccessToken(accessToken);
            vivoDingConf.setAccTokenTime(new Date());
            vivoDingConf.setTicket(ticket);
            vivoDingConf.setTicketTime(new Date());

            vivoDingConfService.save(vivoDingConf);
        }
    }

	/**
	 * 批量删除钉钉接入管理
	 */
	@RequiresPermissions("system:vivoDingConf:edit")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			vivoDingConfService.delete(vivoDingConfService.get(id));
		}
		addMessage(redirectAttributes, "删除钉钉接入管理成功");
		return "redirect:"+Global.getAdminPath()+"/system/vivoDingConf/?repage";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("system:vivoDingConf:edit")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(VivoDingConf vivoDingConf, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "钉钉接入管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<VivoDingConf> page = vivoDingConfService.findPage(new Page<VivoDingConf>(request, response, -1), vivoDingConf);
    		new ExportExcel("钉钉接入管理", VivoDingConf.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出钉钉接入管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/vivoDingConf/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("system:vivoDingConf:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<VivoDingConf> list = ei.getDataList(VivoDingConf.class);
			for (VivoDingConf vivoDingConf : list){
				try{
					vivoDingConfService.save(vivoDingConf);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条钉钉接入管理记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条钉钉接入管理记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入钉钉接入管理失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/vivoDingConf/?repage";
    }

	/**
	 * 下载导入{functionNameSimple}数据模板
	 */
	@RequiresPermissions("system:vivoDingConf:edit")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "钉钉接入管理数据导入模板.xlsx";
    		List<VivoDingConf> list = Lists.newArrayList();
    		new ExportExcel("钉钉接入管理数据", VivoDingConf.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/vivoDingConf/?repage";
    }

}